import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {Product2Service} from "../../../../shared/services/product2/product.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ConfigService} from "../../../../shared/services/config.service";
import {CartService} from "./cart.service";
import {CartComponent} from "./cart/cart.component";

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit, OnDestroy {

    @ViewChild('cartDrawer', {static: false}) cartDrawer: CartComponent;

    option: any = {
        fields: ['name', 'code'],
        keyword: '',
        catalog: 'all',
        category: 'all',
        catalogs: [],
        categories: []
    };

    products: any = [];
    _products: any = [];


    constructor(private router: Router, public route: ActivatedRoute, private productService: Product2Service, public configService: ConfigService, public cartService: CartService,
                private message: NzMessageService, private modal: NzModalService) {
    }

    ngOnInit() {
        this.option.catalogs = this.configService.config.product.catalogs;
        this.productService.getAll()
            .subscribe(res => {
                this._products = res;
                this.clear();
            });
    }

    ngOnDestroy(): void {

    }

    clear() {
        this.option.keyword = '';
        this.filter();
    }

    filter() {
        this.products = this._products.filter(item => {
            if (this.option.catalog != 'all' && item.catalog != this.option.catalog) {
                return false;
            } else {
                if (this.option.category != 'all' && item.category != this.option.category) {
                    return false;
                }
            }
            if (this.option.keyword.trim() === '') {
                return true;
            } else {
                return this.option.fields.some(field => {
                    if (item[field].indexOf(this.option.keyword) != -1) {
                        return true;
                    }
                    return false;
                });
            }
        });
    }


    activeType1() {
        if (this.option.catalog == 'all') {
            this.option.categories = [];
        } else {
            const catalog = this.option.catalogs.find(item => item.code == this.option.catalog);
            this.option.categories = catalog.children;
        }
        this.option.category = 'all';
        this.filter();
    }

    activeType2() {
        this.filter();
    }

    sell(product) {
        this.cartService.add(product);
        this.cartDrawer.show();
    }

}
